<template>
  <div class="container">
    <h1>修改个人信息</h1>
    <div class="row">
      <div class="col-md-4">
        <form @submit.prevent="onSubmit">
          <div class="form-group">
            <label for="name">名字</label>
            <input type="text" v-model="profileForm.name" class="form-control" id="name" placeholder="">
          </div>
          <div class="form-group">
            <label for="location">位置</label>
            <input type="text" v-model="profileForm.location" class="form-control" id="location" placeholder="">
          </div>
          <div class="form-group">
            <label for="about_me">关于我</label>
            <textarea v-model="profileForm.about_me" class="form-control" id="about_me" rows="5"
                      placeholder=""></textarea>
          </div>
          <button type="submit" class="btn btn-primary">提交</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
  import store from '../store.js'

  export default {
    name: "EditProfile",
    data() {
      return {
        sharedState: store.state,
        profileForm: {
          name: '',
          location: '',
          about_me: '',
          submitted: false  // 是否点击了 submit 按钮
        }
      }
    },
    methods: {
      getUser(id) {
        const url = `/users/${id}`;
        this.$axios.get(url)
          .then((resp) => {
            this.profileForm.name = resp.data.name;
            this.profileForm.location = resp.data.location;
            this.profileForm.about_me = resp.data.about_me;
          })
          .catch((error) => {
            console.log('EditProfile getUser==>', error)
          })
      },
      onSubmit(e) {
        const user_id = this.sharedState.user_id;
        const url = `users/${user_id}`;
        const payload = {
          name: this.profileForm.name,
          location: this.profileForm.location,
          about_me: this.profileForm.about_me,
        };

        this.$axios.put(url, payload)
          .then((resp) => {
            this.$toasted.success('个人信息修改成功！', { icon: 'fingerprint' });
            this.$router.push({
              name: 'Profile',
              params: { id: user_id }
            })
          })
          .catch((error) => {
            console.log('EditProfile onSubmit==>', error.response.data)
          })

      }

    },
    created() {
      const user_id = this.sharedState.user_id;
      this.getUser(user_id);
    }
  }
</script>

<style scoped>

</style>
